﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CO2FixCalibration
{
    class FitTimeAxis
    {
        static int LastOptTimeShift;

        public static CalibrationLibrary.Parameters GetHarvestYears(DataSet Modeled, DataSet ModeledCommBiom, DataSet measured, CalibrationLibrary.Parameters parameters)
        {
             
            double measuredbiomass = measured.GetValueAtTime(measured.FirstTime);

            for (int t = Modeled.FirstTime; t < Modeled.LastTime; t++)
            {
                double simulatedbiom = Modeled.GetValueAtTime(t);
                if (simulatedbiom > measuredbiomass)
                {
                    //HY_CNV1
                    parameters["HY_"+ measured.Label].RunningValue = t;

                    LastOptTimeShift = measured.FirstTime - t +1;
                    Modeled.IncreaseTime(LastOptTimeShift);
                    ModeledCommBiom.IncreaseTime(LastOptTimeShift);

                    return parameters;
                }
            }
             
            return parameters;
        }

        public static DataSet[] ShiftAxisAsLast(DataSet Modeled, DataSet ModeledCommBiom)
        {
            Modeled.IncreaseTime(LastOptTimeShift);
            ModeledCommBiom.IncreaseTime(LastOptTimeShift);

            return new List<DataSet>() { new DataSet(Modeled), new DataSet(ModeledCommBiom) }.ToArray(); 
        }
         
        public static DataSet[] Optimize(DataSet Measured, DataSet Modeled, DataSet ModeledCommBiom)
        {
            DataSet[] Data=null;

            double RSSmin = double.MaxValue;
            for (int t = Measured.FirstTime; t > 1600; t--)
            {
                DataSet SuggestedDataSet = new DataSet(Modeled);
                DataSet SuggestedModeledCommBiom = new DataSet(ModeledCommBiom);
               
                SuggestedDataSet.IncreaseTime(t);
                SuggestedModeledCommBiom.IncreaseTime(t);

                int pointsfound;
                double RSS = Statistics.CalculateRSS(Measured, SuggestedDataSet, out pointsfound);

                if (RSS < RSSmin && pointsfound == Measured.NrOfPoints)
                {
                    LastOptTimeShift = t;
                    RSSmin = RSS;

                    Data = new List<DataSet>() { new DataSet(SuggestedDataSet), new DataSet(SuggestedModeledCommBiom) }.ToArray();
                }
            }
            return Data;
        }
        
    }
}
